<template>
  <div>
    <el-dialog v-model="visiable" title="新增用户信息">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >新增</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { studentReg } from "@/service/userService";
import { ElMessage } from "element-plus";
let props = defineProps(["flag"]); //获取数据
let emits = defineEmits(["setFlag", "addInfo"]); //获取方法
let visiable = computed({
  set(value) {
    emits("setFlag", value);
  },
  get() {
    //取值
    return props.flag;
  },
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  username: "",
});
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "长度只能是2到10位", trigger: "blur" },
  ],
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const { data } = await studentReg({ ...ruleForm });
      if (data.code == 200) {
        ElMessage({
          message: "新增成功啦",
          type: "success",
        });
        emits("setFlag", false);
        emits("addInfo", data.result[0]);
      } else {
        ElMessage({
          message: data.msg,
          type: "warning",
        });
      }
    } else {
    }
  });
}; //重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  emits("setFlag", false);
};
</script>

<style></style>
